package cn.feizhu.aimarket.service.impl;

import ch.qos.logback.core.util.MD5Util;
import cn.feizhu.aimarket.exception.ErrorCode;
import cn.feizhu.aimarket.exception.ThrowUtils;
import cn.feizhu.aimarket.model.domain.Book;
import cn.feizhu.aimarket.model.dto.user.UserLoginRequest;
import cn.feizhu.aimarket.model.vo.BookVO;
import cn.feizhu.aimarket.model.vo.UserVO;
import cn.feizhu.aimarket.service.BookService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.feizhu.aimarket.model.domain.User;
import cn.feizhu.aimarket.service.UserService;
import cn.feizhu.aimarket.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
* @author wsdsb
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-10-12 13:03:42
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private BookService bookService;

    @Override
    public Long login(UserLoginRequest userLoginRequest) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = DigestUtil.md5Hex16(userLoginRequest.getUserPassword());
        ThrowUtils.throwIf(StrUtil.isBlank(userAccount) || StrUtil.isBlank(userPassword), ErrorCode.PARAMS_ERROR);
        User user = this.lambdaQuery()
                .eq(User::getUserAccount, userAccount)
                .one();
        if(user == null) {
            // 注册用户
            user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(userPassword);
            // 注意：userRole字段在数据库中有默认值'user'，所以不需要显式设置
            // 如果需要创建管理员用户，可以手动设置：user.setUserRole("admin");
            this.save(user);
        } else {
            // 校验密码 因为首先是根据account从数据库中查的
            if(!user.getUserPassword().equals(userPassword)) {
                ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "用户密码错误");
            }
        }
        return user.getId();
    }

    @Override
    public UserVO getUserInfo(long userId) {
        ThrowUtils.throwIf(userId <= 0, ErrorCode.PARAMS_ERROR, "用户Id不合法");
        User user = this.getById(userId);
        if(user == null) {
            ThrowUtils.throwIf(true, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 如果应用id为空就是全部查询
     * @param userId
     * @param appId
     * @return
     */
    @Override
    public List<BookVO> listMyBooks(long userId, Long appId) {
        List<Book> list = bookService.query()
                .eq("user_id", userId)
                .eq(appId != null, "app_id", appId)
                .orderByDesc("create_time")
                .list();
        return list.stream().map(book -> {
            BookVO bookVO = new BookVO();
            BeanUtils.copyProperties(book, bookVO);
            return bookVO;
        }).toList();
    }
}




